package com.example.indenture.user.controller;

import com.example.indenture.common.service.ImageService;
import com.example.indenture.common.vo.Result;
import com.example.indenture.common.vo.Search;
import com.example.indenture.user.entity.User;
import com.example.indenture.user.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ImageService imageService;



    @PostMapping(value = "/user/insert", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<User> insertUser(@RequestBody User user,HttpSession httpSession) {
        user.setState(1);
        return userService.insertUser(user,httpSession);
    }

    @RequestMapping(value = "/user/delete/{id}")
    public Result<Object> deleteUserById(@PathVariable int id) {
        return userService.deleteUserById(id);
    }

    @PutMapping(value = "/user/update", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<Object> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @PostMapping(value = "/user/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<User> loginInUser(@RequestBody User user, HttpSession httpSession) {
        return userService.loginInUser(user.getUserName(), user.getPassword(), httpSession);
    }

    @PostMapping(value = "/user/loginFace", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<User> loginInUserFace(@RequestBody User user, HttpSession httpSession) {
        return userService.loginInUser(user.getUserName(), user.getUrl(), httpSession);
    }

    @PostMapping(value = "/user/image/{imageTypeName}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadImage(
            @RequestParam MultipartFile mf,
            @RequestParam Integer id,
            @PathVariable String imageTypeName) {
        Result<String> result = imageService.uploadImage(mf, imageTypeName);
        String url = result.getData();
        userService.updateUserUrl(id, url);
        return result;
    }

    @PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE)
    public PageInfo<User> getUsersBySearch(@RequestBody Search search) {
        return userService.getUsersBySearch(search);
    }

    @PostMapping(value = "/user/getById", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<Integer> getIdByName(@RequestBody Search search) {
        return userService.getIdByName(search.getKeyword());
    }
    @RequestMapping("/test")
    public Integer helleo(){
        return 1;
    }
}
